"""
cdn.server_api

Defines the API for communication between cdn servers.

Currently, this is basically just the client_api.
"""
### Start of imports

# This line just better work...
from jackson import debug

# There's debug stuff for the rest
debug.pre_import(__name__)
from django.conf import settings
from jackson.cdn.client_api import get_url
from jackson.cdn.models import ContentEntry
from jackson.cdn import sync
from jackson.cdn import core
debug.post_import(__name__)

### End of imports


def confirm_distribution_handler(the_key):
    """
    Deletes content specified by key from disk and ContentEntry table
    """
    context = [__name__, 'confirm_distribution_handler()']
    try:
        debug.enter(context, { 'key' : the_key })
        debug.comment(context,"calling into core from (server_api)confirm_distribution_handler()")
        ans = core.delete_content_by_key(the_key)
        try:
            entry = ContentEntry.objects.get(key=the_key)
            entry.delete()
        except Exception, e:
            debug.exception(context, "Exception while trying to delete ContentEntry: " + str(e))
    except Exception, e:
        ans = False
        debug.exception(context,"problem with confirm_distribution," + str(e))
    debug.leave(context, { 'success?' : ans })
    return ans


def confirm_distribution_handler_old(the_key):
    """ Returns True if this server has a good copy of the content associated with key, False otherwise.
    @author: ep
    @rtype: True or False
    """
    try:
        entry = ContentEntry.objects.get(key=the_key)
        if entry.status in [ 'H', 'O' ]:
            return True
        else:
            return False
    except:
        return False

def delegate_keys_handler(d):
    """ This function is called to inform this server that it will be receiving new keys.
    @todo: make this call sync.collect_content()
    @author: ep
    @rtype: None
    """
    context = [__name__, 'delegate_keys_handler()']
    debug.enter(context, { 'd' : d })
    try:
        # For every key in dict
        for the_key, info in d.items():
            # Try creating a ContentEntry for key marked Incoming from server
            entry = ContentEntry(key=the_key)
            #entry.url = info['url'] 
            entry.filename = info["filename"]
            entry.mimetype = info["mimetype"]
            entry.server = info["server"]
            entry.status = 'I'
            entry.md5_checksum = info["md5_checksum"]
            entry.save()
            core.get_content(entry)
#            if entry.mimetype == 'IP':
#                core.get_content(entry)
#        for the_key in d.keys():
#            entry = ContentEntry(key=the_key)
#            if entry.status == 'I':
#                core.get_content(entry)
        num_transferred = len(d.keys())
        
        result = { 'number_keys_transferred':num_transferred }
    except Exception, e:
        debug.exception(context, str(e))
        result = { 'exception' : str(e)}
    debug.leave(context, result)
    return result

def is_hosting_handler(the_key):
    """ Returns True if this host is responsible for and serving the file for key.
    @author: ep
    @rtype: True or False
    """
    try:
        entry = ContentEntry.objects.get(key=the_key)
        return entry.status == 'H'
    except:
        return False

def poke_handler(the_key):
    """ Increases the urgency of the associated ContentEntry.
    @author: ep
    @rtype: True if the poke was successful, False otherwise
    """
    try:
        entry = ContentEntry.objects.get(key=the_key)
        entry.urgency = entry.urgency + settings.POKE_URGENCY_INCREMENT
        entry.save()
        return True
    except:
        return False

def redirect_key_handler(the_key, new_server):
    """ Sets the server of a ContentEntry to new_server.
    @author: ep
    @rtype: None
    """
    try:
        entry = ContentEntry.objects.get(key=the_key)
        entry.server = new_server
        entry.save()
        return
    except:
        return
